#include "communicationwindow.h"
#include "ui_communicationwindow.h"

CommunicationWindow::CommunicationWindow(QTcpSocket * clientSocket,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::CommunicationWindow)
    , clientSocket(clientSocket)
{
    ui->setupUi(this);

    QPixmap pixmap("../../../resource/4.jpg");
    QPalette palette;
    palette.setBrush(QPalette::Window, pixmap);
    this->setPalette(palette);
    this->setWindowTitle("医患交流平台");

    // 添加图片发送按钮
    imageButton = new QPushButton("发送图片", this);
    imageButton->setGeometry(450, 350, 80, 30); // 根据界面调整位置
    imageButton->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; border: none; border-radius: 4px; }");
    connect(imageButton, &QPushButton::clicked, this, &CommunicationWindow::on_ImageButton_clicked);

    // 获取医生列表（原有代码保持不变）
    QString doctorQueryStr = "SELECT doctor_id, name FROM Doctors;";
    clientSocket->write(doctorQueryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000);

    if (clientSocket->waitForReadyRead(3000)) {
        QByteArray data = clientSocket->readAll();
        QString receivedData = QString::fromUtf8(data);

        if (receivedData == "failed") {
            QMessageBox::warning(this, tr("Error"), tr("No Doctor in data base;\nPlease connect workers."));
            exit(888);
        } else {
            QStringList items = receivedData.split('\n');
            for (const QString &item : items) {
                if(item.length()<3)
                    continue;
                ui->DoctorBox->addItem(item);
            }
        }
    } else {
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }

    timer = new QTimer(this);
    timer->start(1000);
    connect(timer, &QTimer::timeout, this, &CommunicationWindow::DialogEdit_update);
}

void CommunicationWindow::on_DoctorBox_currentIndexChanged(){
    ui->DialogEdit->clear();
    qDebug()<< "Selected option: " << ui->DoctorBox->currentText();

    QString selectDoctorStr = ui->DoctorBox->currentText();
    QString doctorIDStr = selectDoctorStr.section('|', 0, 0);
    QString patientIDStr = QString::number(currentUserID);

    // 修改查询以支持图片消息
    QString dialogQueryStr = "SELECT * FROM Chats WHERE patient_id = "+patientIDStr+
                             " AND doctor_id = "+doctorIDStr+" ORDER BY date ASC;";
    clientSocket->write(dialogQueryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000);

    if (clientSocket->waitForReadyRead(3000)) {
        QByteArray data = clientSocket->readAll();
        QString receivedData = QString::fromUtf8(data);

        if (receivedData == "failed") {
            ;
        } else {
            QStringList items = receivedData.split('\n');
            for (const QString &item : items) {
                qDebug()<<item;
                QStringList atomItems = item.split('|');
                if(atomItems.size()<6)
                    break;

                // 检查消息类型
                QString messageType = atomItems.size() > 6 ? atomItems[6] : "text";

                if(atomItems[3]=="incoming") {
                    // 医生发给患者的消息
                    ui->DialogEdit->append(QString("<span style='color: red;'>") +
                                           selectDoctorStr.section('|', 1, 1) + QString("</span>"));

                    if (messageType == "image") {
                        QString fileName = atomItems.size() > 7 ? atomItems[7] : "未知图片";
                        ui->DialogEdit->append("<span style='color: green;'>[图片: " + fileName + "]</span>");
                    } else {
                        ui->DialogEdit->append(QString("<span style='color: black;'>") + atomItems[5] + QString("</span>"));
                    }
                } else {
                    // 患者发给医生的消息
                    ui->DialogEdit->append(QString("<span style='color: blue;'>您</span>"));

                    if (messageType == "image") {
                        QString fileName = atomItems.size() > 7 ? atomItems[7] : "未知图片";
                        ui->DialogEdit->append("<span style='color: green;'>[图片: " + fileName + "]</span>");
                    } else {
                        ui->DialogEdit->append(QString("<span style='color: black;'>") + atomItems[5] + QString("</span>"));
                    }
                }
            }
        }

        QScrollBar *scrollBar = ui->DialogEdit->verticalScrollBar();
        scrollBar->setValue(scrollBar->maximum());
    } else {
        QMessageBox::warning(this, tr("Error"), tr("No response from the server."));
        exit(999);
    }
}

void CommunicationWindow::on_ImageButton_clicked() {
    // 检查是否选择了医生
    if (ui->DoctorBox->currentText().isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择一个医生");
        return;
    }

    // 选择图片文件
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "选择图片",
        "",
        "Images (*.png *.jpg *.jpeg *.bmp *.gif)"
        );

    if (fileName.isEmpty()) {
        return;
    }

    // 读取图片文件
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, "错误", "无法读取图片文件");
        return;
    }

    QByteArray imageData = file.readAll();
    file.close();

    // 检查文件大小（限制为5MB）
    if (imageData.size() > 5 * 1024 * 1024) {
        QMessageBox::warning(this, "错误", "图片文件过大，请选择小于5MB的图片");
        return;
    }

    // 获取医生ID
    QString selectDoctorStr = ui->DoctorBox->currentText();
    int doctorId = selectDoctorStr.section('|', 0, 0).toInt();

    // 构造JSON消息
    QJsonObject json;
    json["patient_id"] = currentUserID;      // 患者ID
    json["doctor_id"] = doctorId;            // 医生ID
    json["direction"] = "outgoing";          // 患者发给医生
    json["filename"] = QFileInfo(fileName).fileName();
    json["image_data"] = QString::fromUtf8(imageData.toBase64());

    // 发送JSON消息
    QJsonDocument doc(json);
    QString jsonString = doc.toJson(QJsonDocument::Compact) + "\n";

    clientSocket->write(jsonString.toUtf8());
    clientSocket->flush();

    // 等待服务器响应
    if (clientSocket->waitForReadyRead(3000)) {
        QByteArray response = clientSocket->readAll();
        QString responseStr = QString::fromUtf8(response);

        if (responseStr.startsWith("success:")) {
            // 在聊天框中显示图片消息
            ui->DialogEdit->append("<span style='color: blue;'>您</span>");
            ui->DialogEdit->append("<span style='color: green;'>[图片: " + QFileInfo(fileName).fileName() + "]</span>");

            // 滚动到底部
            QScrollBar *scrollBar = ui->DialogEdit->verticalScrollBar();
            scrollBar->setValue(scrollBar->maximum());

            QMessageBox::information(this, "成功", "图片发送成功");
        } else {
            QMessageBox::warning(this, "错误", "图片发送失败: " + responseStr);
        }
    } else {
        QMessageBox::warning(this, "错误", "发送超时，请重试");
    }
}

void CommunicationWindow::on_BackButton_clicked(){
    emit back();
}

void CommunicationWindow::on_SendButton_clicked(){
    QString sendContent = ui->SendEdit->toPlainText();
    QString selectDoctorStr = ui->DoctorBox->currentText();
    QString doctorIDStr = selectDoctorStr.section('|', 0, 0);
    QString patientIDStr = QString::number(currentUserID);

    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString formattedDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");

    QString queryStr = "INSERT INTO Chats (patient_id, doctor_id, direction, date, content, message_type) "
                       "VALUES (" + patientIDStr + ", " + doctorIDStr + ", 'outgoing', '" + formattedDateTime + "', '" + sendContent + "', 'text');";

    clientSocket->write(queryStr.toUtf8());
    clientSocket->waitForBytesWritten(1000);

    ui->SendEdit->clear();
}

void CommunicationWindow::DialogEdit_update(){
    on_DoctorBox_currentIndexChanged();
}

CommunicationWindow::~CommunicationWindow()
{
    delete ui;
}
